package com.je.gateway.xml;

import com.google.common.base.Strings;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.FileNotFoundException;
import java.io.IOException;

public abstract class AbstractXmlConfigResourceLoader<T> implements ConfigResourceLoader<T> {

    private static final Logger logger = LoggerFactory.getLogger(AbstractXmlConfigResourceLoader.class);

    private String resourcePath;

    public String getResourcePath() {
        return resourcePath;
    }

    public void setResourcePath(String resourcePath) {
        this.resourcePath = resourcePath;
    }

    public AbstractXmlConfigResourceLoader(String resourcePath) {
        this.resourcePath = resourcePath;
    }

    private Element read(){
        if(Strings.isNullOrEmpty(resourcePath)){
            logger.error("The xml config resource path is null!");
        }
        Element rootElement = null;
        SAXReader reader = new SAXReader();
        try {
            ClassPathResource classPathResource = new ClassPathResource(resourcePath);
            Document document = reader.read(classPathResource.getInputStream());
            rootElement = document.getRootElement();
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error("require config from path {} is error!",resourcePath);
            System.exit(0);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error("require config from path {} is error!",resourcePath);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rootElement;
    }

    public abstract T parse(Element rootElement);

    @Override
    public T load() {
        Element rootElement = read();
        return parse(rootElement);
    }

}
